package com.acmen.easyapi.aspect;

import com.acmen.easyapi.annotation.DummyData;
import com.acmen.easyapi.builder.ResponseDataBuilder;
import com.acmen.easyapi.model.Response;
import com.acmen.easyapi.util.FileLoader;
import com.acmen.easyapi.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @author chenyingjun
 * 通过注解切面controller服务
 * @date 2023-10-30
 */
@Aspect
@Component
public class DummyDataAspect {

    @Resource
    private ResponseDataBuilder apiDataBuilder;
    /**
     * 在方法调用前的切面方法，用于处理dummyData注解
     * @param joinPoint 提供关于被拦截方法的信息
     * @param dummyData dummyData注解对象
     * @return 返回处理后的结果
     */
    @Around("@annotation(dummyData)")
    public Object around(ProceedingJoinPoint joinPoint, DummyData dummyData) {
        // 判断dummyData的jsonPath是否非空
        if(StringUtil.isNotEmpty(dummyData.jsonPath())){
            // 从资源文件中读取json数据
            String json = FileLoader.fromResource(dummyData.jsonPath());
            // 将json数据解析为JSON对象并返回
            return Response.of(JSON.parse(json));
        }

        // 获取方法对象
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        // 根据方法的返回类型构建一个空的JSON对象
        JSON json = apiDataBuilder.buildData(method.getGenericReturnType());
        // 返回构建的JSON对象
        return Response.of(json);

    }

}
